package com.csp.mingyue.auth.controller;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.stp.SaTokenInfo;
import com.csp.mingyue.auth.dto.EmailLoginDto;
import com.csp.mingyue.auth.dto.PasswordLoginDto;
import com.csp.mingyue.auth.dto.RegisterDto;
import com.csp.mingyue.auth.dto.SmsLoginDto;
import com.csp.mingyue.auth.service.SysLoginService;
import com.csp.mingyue.common.core.vo.R;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Objects;

/**
 * @author Strive
 * @date 2023/6/29 13:47
 */
@Tag(name = "TokenController", description = "Token(令牌) 相关接口")
@Slf4j
@RestController
@RequiredArgsConstructor
public class TokenController {

	private final SysLoginService sysLoginService;

	/**
	 * 登录接口
	 */
	@PostMapping("/login")
	@Operation(summary = "登录接口")
	public R<String> doLogin(@RequestBody @Valid PasswordLoginDto dto) {
		log.info("------- 进入【登录接口】请求: " + SaHolder.getRequest().getUrl());
		// 用户登录
		SaTokenInfo login = sysLoginService.login(dto);

		if (Objects.isNull(login)) {
			return R.fail("登录失败");
		}

		return R.ok("登录成功", login.getTokenValue());
	}

	/**
	 * 短信登录
	 */
	@PostMapping("/smsLogin")
	@Operation(summary = "短信登录")
	public R<String> smsLogin(@RequestBody @Valid SmsLoginDto dto) {
		log.info("------- 进入【短信登录】请求: " + SaHolder.getRequest().getUrl());
		// 用户登录
		SaTokenInfo login = sysLoginService.smsLogin(dto);

		if (Objects.isNull(login)) {
			return R.fail("登录失败");
		}

		return R.ok("登录成功", login.getTokenValue());
	}

	/**
	 * 邮箱登录
	 */
	@PostMapping("/emailLogin")
	@Operation(summary = "邮箱登录")
	public R<String> emailLogin(@RequestBody @Valid EmailLoginDto dto) {
		log.info("------- 进入【邮箱登录】请求: " + SaHolder.getRequest().getUrl());
		// 用户登录
		SaTokenInfo login = sysLoginService.emailLogin(dto);

		if (Objects.isNull(login)) {
			return R.fail("登录失败");
		}

		return R.ok("登录成功", login.getTokenValue());
	}

	/**
	 * 登出接口
	 */
	@DeleteMapping("logout")
	@Operation(summary = "登出接口")
	public R<Void> logout() {
		sysLoginService.logout();
		return R.ok();
	}

	/**
	 * 用户注册
	 */
	@PostMapping("register")
	@Operation(summary = "用户注册")
	public R<Void> register(@RequestBody RegisterDto dto) {
		sysLoginService.register(dto);
		return R.ok();
	}

}
